package org.smart4j.framework.util;

import org.apache.log4j.Logger;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * Created by Lin on 2018/03/29.
 */
public final class PropsUtil {
    private static final Logger logger = Logger.getLogger(PropsUtil.class);

    public static Properties loadProps(String filename) {
        Properties props = null;
        InputStream in = null;
        try{
            in = Thread.currentThread().getContextClassLoader().getResourceAsStream(filename);
            if(in == null) {
                throw new FileNotFoundException(filename + "not find");
            }
            props = new Properties();
            props.load(in);
        } catch (IOException e) {
            logger.error("props load file error", e);
        } finally {
            if(in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    logger.error("close error", e);
                }
            }
        }
        return props;
    }

    public static String optString(Properties props, String key) {
        return getString(props, key, "");
    }
    /**
     * 获取字符型数据
     * @param props
     * @param key
     * @param defaultValue
     * @return
     */
    public static String getString(Properties props, String key, String defaultValue) {
        String value = defaultValue;
        if(props.containsKey(key)) {
            value = props.getProperty(key);
        }
        return value;
    }

    public static int optInt(Properties props, String key) {
        return getInt(props, key, 0);
    }

    public static int getInt(Properties props, String key, int defaultValue) {
        int value = defaultValue;
        if(props.containsKey(key)) {
            value = CastUtil.castInt(props.getProperty(key));
        }
        return value;
    }
}
